package controllers;

import controllers.common.ControllerBase;
import dao.common.ImageManager;
import dao.hibernate.ImageManagerHB;
import models.helpers.ImageHelper;
import play.Play;

import java.io.IOException;
import java.io.InputStream;

public class Image extends ControllerBase {
    private static ImageManager imageManager = new ImageManagerHB();
    public static void get(int id, String entityName, Integer width, Integer height, Boolean crop) throws IOException {
        if (crop == null){
            crop = true;
        }
        width = checkImageConstraints(width);
        height = checkImageConstraints(height);
        models.shop.Image image = imageManager.getById(id);
        InputStream stream = ImageHelper.getImage(Play.getFile("data").toString(), image, width, height, entityName, crop);
        setCache(1000000);
        renderBinary(stream, String.format("%1$s_%2$sx%3$s.jpg", id, width, height), "image/jpg", true);
    }

    private static Integer checkImageConstraints(Integer size) {
        if (size == null || size < 20 || size > 1000){
            size = 100;
        }
        return size;
    }

}
